package main;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

//(among others) Handles tha data download and process
public class DataHandler
{
    public static Hashtable currencies;
    public static int queuePointer=0;
    
    public static String[] currencyNames=new String[]{
        "EUR",
        "USD",
        "GBP",
        "JPY",
        "CAD",
        "CHF",
        "NZD",
        "INR"
    };
    
    //Download the rates from an rss feed
    public static void downloadRates() throws IOException 
    {
        HttpConnection httpConn = null;
        String url = "http://themoneyconverter.com/EUR/rss.xml";
        
        InputStream is = null;
        OutputStream os = null;

        try
        {
            mainMIDlet.canvas.requestMessageToBeShown("Making connection...");
            httpConn = (HttpConnection)Connector.open(url);
            httpConn.setRequestMethod(HttpConnection.GET);
            
            mainMIDlet.canvas.requestMessageToBeShown("Requesting data...");
            
            int respCode = httpConn.getResponseCode();
            if (respCode == httpConn.HTTP_OK)
            {
                mainMIDlet.canvas.requestMessageToBeShown("Downloading data...");
                
                StringBuffer sb = new StringBuffer();
                os = httpConn.openOutputStream();
                is = httpConn.openDataInputStream();
                int chr;
                while ((chr = is.read()) != -1)
                    sb.append((char) chr);
                
                processRates(sb.toString());
                
                mainMIDlet.canvas.requestMessageToBeShown("Data downloaded and saved!");
                mainMIDlet.canvas.requestClearMessage();
            }
            else
            {
                System.out.println("Error in opening HTTP Connection. Error#" + respCode);
            }
            
        }
        catch (Exception ex)
        {
            mainMIDlet.canvas.requestMessageToBeShown("Connection not allowed by user...");
            mainMIDlet.canvas.requestClearMessage();
        }
        finally
        {
            if(is!= null)
                is.close();
            if(os != null)
                os.close();
            if(httpConn != null)
                httpConn.close();
        }
    }
    
    //Parse the data download to fill the rates tables
    private static void processRates(String ratesData)
    {
        mainMIDlet.canvas.requestMessageToBeShown("Processing data...");
        
        float[] rates=new float[currencyNames.length];
        rates[0]=1f;
        
        int itemPosition=ratesData.indexOf("<title>");
        String currentCurrency="";
        float rateValue=0f;
        while (itemPosition>=0)
        {
            ratesData=ratesData.substring(itemPosition+"<title>".length());
            currentCurrency=ratesData.substring(0,ratesData.indexOf("/"));
            int currencyIndex=indexOfCurrency(currentCurrency);
            if (currencyIndex>=0)
            {
                ratesData=ratesData.substring(ratesData.indexOf("1 Euro = ")+"1 Euro = ".length());
                rateValue=Float.parseFloat(ratesData.substring(0,ratesData.indexOf(" ")));
                rates[currencyIndex]= rateValue;
            }
            itemPosition=ratesData.indexOf("<title>");
        }
        
        updateCurrencyData(rates,true);
    }
    
    public static int indexOfCurrency(String currency)
    {
        for (int i=0;i<currencyNames.length;i++)
        {
            if (currencyNames[i].equals(currency))
            {
                return i;
            }
        }
        return -1;
    }
    
    //updates the rates tables of all the currencies
    public static void updateCurrencyData(float[] rates, boolean updateStore)
    {
        currencies=new Hashtable();
        for (int i=0;i<currencyNames.length;i++)
        {
            Currency newCurrency=new Currency(currencyNames[i], rates);
            currencies.put(newCurrency.getName(), newCurrency);
        }
        
        if (updateStore)
        {
            StorageHandler.storeRates(rates);
        }
    }
    
    //Selects the first currency in the queue of the non visible currencies
    //(Used when swipping a currency to replace it with another)
    public static String getNextNonDisplayedCurrency()
    {
        for (int i=queuePointer;i<currencyNames.length;i++)
        {
            boolean itIsDisplayed=false;
            for (int j=0;j<4;j++)
            {
                if (currencyNames[i].equals(MainCanvas.displayedCurrencies[j]))
                {
                    itIsDisplayed=true;
                    break;
                }
            }
            if (!itIsDisplayed)
            {
                queuePointer=(i==currencyNames.length-1)?0:(i+1);
                return currencyNames[i];
            }
        }
        
        queuePointer=0;
        return getNextNonDisplayedCurrency();
    }
}
